# -*- coding: utf-8 -*- 

###########################################################################
## Python code generated with wxFormBuilder (version Sep  8 2010)
## http://www.wxformbuilder.org/
##
## PLEASE DO "NOT" EDIT THIS FILE!
###########################################################################

import wx
import glob
import os
import math
import win32api

import linkparse


###########################################################################
## Class lnkPopWin
###########################################################################

FILEPATH = 0
FILEICON = 1
DEFINE_ICON = 'bmp/define.png'

class lnkPopWin ( wx.Frame ):
    
    def __init__( self, parent, lnkdict=None, #bmpdir=None,
                  bg=wx.SYS_COLOUR_ACTIVEBORDER, rect=(0, 0, 0, 0)):
        wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition,
                            size = wx.Size( 400,300 ), style = 0|wx.TAB_TRAVERSAL )
        self.dictLnk = lnkdict
        #self.bmpdir = bmpdir

        self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
        
        gSizer = wx.GridSizer( 1, 1, 0, 0 )
        
        self.m_listCtrl_LNK_ICO = wx.ListCtrl( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,
                                               wx.LC_ICON)
        self.m_listCtrl_LNK_ICO.SetBackgroundColour( wx.SystemSettings.GetColour( bg ) )
        
        gSizer.Add( self.m_listCtrl_LNK_ICO, 0, wx.EXPAND, 5 )
        
    

        self.SetSizer( gSizer )
        self.Layout()
        self.m_menu = wx.Menu()
        self.m_menuItem_close = wx.MenuItem( self.m_menu, wx.ID_ANY, u"Close", wx.EmptyString, wx.ITEM_NORMAL )
        self.m_menu.AppendItem( self.m_menuItem_close )
        
        self.Bind( wx.EVT_RIGHT_DOWN, self.lnkPopWinOnContextMenu ) 
        
        
        self.Centre( wx.BOTH )
        
         ## 创建定时器  
        #self.timer = wx.Timer(self)#创建定时器  
        #self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)#绑定一个定时器事件 
        
        # Connect Events
        self.m_listCtrl_LNK_ICO.Bind( wx.EVT_LIST_ITEM_SELECTED, self.m_listCtrl_LNK_ICOOnListItemSelected )
        self.m_listCtrl_LNK_ICO.Bind( wx.EVT_RIGHT_DOWN, self.m_listCtrl_LNK_ICOOnRightDown )
        self.Bind( wx.EVT_MENU, self.m_menuItem_closeOnMenuSelection, id = self.m_menuItem_close.GetId() )
        #self.m_listCtrl_LNK_ICO.Bind( wx.EVT_KILL_FOCUS, self.OnKillFocus )

        self.UpdateLnk(self.dictLnk, rect=rect)

        
    def __del__( self ):
        #self.Destory()
        pass
    
    
    # Virtual event handlers, overide them in your derived class
    #def OnKillFocus(self, event):
        #print 'Kill Focus'
        #self.Hide()
    #def OnTimer(self, event):
        #t = time.localtime(time.time())  
        #StrYMDt = time.strftime("%Y-%B-%d", t)  
        #self.SetStatusText(StrYMDt,0) #显示年月日  
        #StrIMSt = time.strftime("%I:%M:%S", t)  
        #self.SetStatusText(StrIMSt,1)#显示时间 
        #pass
    
    def m_listCtrl_LNK_ICOOnRightDown( self, event ):
#        self.PopupMenu( self.m_menu, event.GetPosition() )
        self.Close()
        event.Skip()
    
    def m_menuItem_closeOnMenuSelection( self, event ):
        self.Close()
        event.Skip()
    
    def lnkPopWinOnContextMenu( self, event ):
        self.PopupMenu( self.m_menu, event.GetPosition() )

    def __get_row_col(self, count):
#        print count
        if count:
            row = math.floor(math.sqrt(math.ceil(float(count) / 2)))
            col = math.ceil(float(count) / row)
        else:
            row = 0
            col = 0
        return (row, col)
    def UpdateLnk(self, dictLnk, rect=(0, 0, 0, 0)):
        '''更新lnk图标,根据传入的lnk词典来更新
        词典key为按钮标题,值为(lnk, file)
        u'Oooo': (u'D:\\Oooo.lnk', u'C:\\Oooo.exe')
        '''
        imgList = wx.ImageList(32, 32)
        self.m_listCtrl_LNK_ICO.ClearAll()
        self.bmpname = []

        for key in dictLnk.keys():
            #bmpfile = os.path.join(self.bmpdir, key + '.bmp')
            bmpfile = dictLnk[key][FILEICON]
            if not os.path.exists(bmpfile):# and linkparse.ExtractIcon2File(dictLnk[key][1], bmpfile) == False:
                bmpfile = DEFINE_ICON
                
            fileext =  os.path.splitext(bmpfile)[1]
            if fileext == '.bmp':
                bmp = wx.Bitmap(bmpfile, wx.BITMAP_TYPE_BMP)
            elif fileext == '.ico':
                bmp = wx.Bitmap(bmpfile, wx.BITMAP_TYPE_ICO)
            elif fileext == '.png':
                bmp = wx.Bitmap(bmpfile, wx.BITMAP_TYPE_PNG)
                       
            
            n = imgList.Add(bmp)
            self.bmpname.append(key)

#        print self.bmpname
        self.m_listCtrl_LNK_ICO.AssignImageList(imgList, wx.IMAGE_LIST_NORMAL)

        for i in range( len(self.bmpname)):
            self.m_listCtrl_LNK_ICO.InsertImageStringItem(i, self.bmpname[i], i)

        # 计算窗口大小
        row, col = self.__get_row_col(len(dictLnk))
#        print 'pop size:', str((row, col))
        if not row or not col:
            self.SetSize((0, 0))
            return
        popwinSize = (col * 80, row * 80 + 20)

        self.SetSize(popwinSize)

        # 计算窗口pos
        winDisplaySize = wx.DisplaySize()

        if rect[1] + rect[3] + popwinSize[1] > winDisplaySize[1]:
            pos = (rect[0], rect[1] - popwinSize[1])
        else:
            pos = (rect[0], rect[1] + rect[3])

        x = pos[0] - (popwinSize[0] - rect[2]) / 2
        y = pos[1]

        if x < 0: x = 0
        if y < 0:  y = 0
        if y + popwinSize[1] > winDisplaySize[1]:
            y = winDisplaySize[1] - popwinSize[1]
        if x + popwinSize[0] > winDisplaySize[0]:
            x = winDisplaySize[0] - popwinSize[0]

        pos = (x, y)

        self.Move(pos)
        

    def m_listCtrl_LNK_ICOOnListItemSelected(self, event):
        file = ''
        text = self.m_listCtrl_LNK_ICO.GetItemText(event.Index)
        if self.dictLnk[text][0]:
            file = self.dictLnk[text][0]
        elif self.dictLnk[text][1]:
            file = self.dictLnk[text][1]
#        print file

        # win32api.ShellExecute 参数如下
        # hwnd : PyHANDLE
        # op : string
        # file : string
        # params : string
        # dir : string
        # bShow : int
        try:
            win32api.ShellExecute(None, None, file, None, None, True)
            self.Hide()
        except:
            pass



    
_curDir = os.path.abspath(os.path.curdir)
_configFile = os.path.join(_curDir, r'config.ini')
_xmlFileDir = os.path.join(_curDir, r'xml')
_icoFileDir = os.path.join(_curDir, r'ico')
_bmpFileDir = os.path.join(_curDir, r'bmp')


dictLnk = {u'\u5378\u8f7dQQ\u5f71\u50cf': (u'D:\\PROGRA~1\\Tencent\\QQImage\\uninst.exe', u'bmp\\\u5378\u8f7dQQ\u5f71\u50cf.bmp'), 
           u'QQ\u97f3\u4e50': (u'D:\\PROGRA~1\\Tencent\\QQMusic\\QQMusic.exe', u'bmp\\QQ\u97f3\u4e50.bmp'), 
           u'QQ\u5f71\u50cf': (u'D:\\PROGRA~1\\Tencent\\QQImage\\bin\\QQImage.exe', u'bmp\\QQ\u5f71\u50cf.bmp'), 
           u'Professional Square QVGA': (u'C:\\PROGRA~1\\MI0836~1\\1.0\\DEVICE~1.EXE', u'bmp\\Professional Square QVGA.bmp'), 
           u'\u5378\u8f7d QQ\u97f3\u4e50': (u'D:\\PROGRA~1\\Tencent\\QQMusic\\QQMUSI~4.EXE', u'bmp\\\u5378\u8f7d QQ\u97f3\u4e50.bmp'), 
           u'SQL Server \u5916\u56f4\u5e94\u7528\u914d\u7f6e\u5668': (u'C:\\PROGRA~1\\MI3EDC~1\\90\\Shared\\SqlSAC.exe', 
                                                                      u'bmp\\SQL Server \u5916\u56f4\u5e94\u7528\u914d\u7f6e\u5668.bmp'), 
           u'\u542f\u52a8\u8fc5\u96f7\u770b\u770b\u64ad\u653e\u5668': (u'D:\\PROGRA~1\\THUNDE~1\\Xmp\\program\\XMP.exe', u'bmp\\\u542f\u52a8\u8fc5\u96f7\u770b\u770b\u64ad\u653e\u5668.bmp'), 
           u'SQL Server \u9519\u8bef\u548c\u4f7f\u7528\u60c5\u51b5\u62a5\u544a': (u'C:\\PROGRA~1\\MI3EDC~1\\90\\Shared\\SqlWtsn.exe', u'bmp\\SQL Server \u9519\u8bef\u548c\u4f7f\u7528\u60c5\u51b5\u62a5\u544a.bmp')}



if __name__ == '__main__':
    app = wx.App()
    frame = lnkPopWin(None, lnkdict=dictLnk, rect=(100, 200, 300, 400))
    frame.Show()
    app.MainLoop()
